package com.spring.demo.webflux.demo.router;

import com.spring.demo.webflux.demo.filter.ExampleHandlerFilterFunction;
import com.spring.demo.webflux.demo.handler.CityHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicate;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * @author wangzhilong
 * @date 2020/7/7
 */
@Configuration
public class CityRouter implements ApplicationContextAware {

    private ApplicationContext applicationContext ;
    /**
     * 基于功能端点的实现  配合 Handler实现
     * RouterFunctions 对请求路由处理类，即将请求路由到处理器。
     * 这里将一个 GET 请求 /hello 路由到处理器 cityHandler 的
     * helloCity 方法上。跟 Spring MVC 模式下的 HandleMapping 的作用类似。
     * @param cityHandler
     * @return
     */
    @Bean
    public RouterFunction<ServerResponse> routerCity(CityHandler cityHandler) {
        final ExampleHandlerFilterFunction filterFunction = applicationContext.getBean(ExampleHandlerFilterFunction.class);
        return RouterFunctions.route(RequestPredicates.GET("/hello/{name}")
                        .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                cityHandler::helloCity)
                //基于路由的过滤器
                .filter(filterFunction);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
